package com.ruoyi.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.aop.CheckUserMark;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.domain.model.XcxLoginBody;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.result.Result;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.*;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.XcxLoginService;
import com.ruoyi.service.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysRoleServiceImpl;
import com.ruoyi.uitity.GetOpenIdUtil;
import com.ruoyi.uitity.MinioUtil;
import com.ruoyi.uitity.WxMessageProducer;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.springframework.web.multipart.MultipartFile;



@RestController
public class AiController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private XcxLoginService xcxLoginService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WxMessageProducer producer;
    @Autowired
    private IT06Service t06Service;
    @Autowired
    private IT07Service t07Service;

    @Autowired
    private AIService aiService;

    @Autowired
    private SysRegisterService registerService;
    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private IT10Service t10Service;

    @Autowired
    private SysRegisterService sysRegisterService;
    @Autowired
    private ISysUserService sysUserService;


    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;
    @PostMapping("/login1")
    @Log(title = "小程序日志", businessType = BusinessType.LOGIN)
    @ApiOperation("小程序登录")
    public AjaxResult login(@RequestBody XcxLoginBody loginUser, HttpServletRequest request) {
        if (StringUtils.isEmpty(loginUser.getUsername()) || StringUtils.isEmpty(loginUser.getPassword())) {
            return AjaxResult.error(HttpStatus.ERROR, "用户名或密码不能为空");
        }
        AjaxResult ajax = AjaxResult.success();
        String token =xcxLoginService.login(loginUser.getUsername(), loginUser.getPassword());
        System.out.println("token"+token);
        ajax.put(Constants.TOKEN, token);
        T06 t06 = t06Service.selectByusername(loginUser.getUsername());
        redisTemplate.opsForValue().set("loginuser:"+t06.getF0601(),t06, 30, TimeUnit.MINUTES);
        return ajax;
    }
    @Autowired
    private SysRoleServiceImpl sysRoleService;
        @ApiOperation("微信测试登录")
        @Log(title = "小程序日志", businessType = BusinessType.LOGIN)
        @PostMapping("/Login1")
        public AjaxResult testLogin(@RequestBody  Codebody body, HttpServletRequest request){
            GetOpenIdUtil getOpenIdUtil=new GetOpenIdUtil();
            String jsonId = null;
            System.out.println("code"+body.getCode());
//            jsonId = getOpenIdUtil.getopenid("wx2e670d3f95a8db39",body.getCode(),"a1620abb1182f602a7489a9b58ef3a3e");
            try {
                jsonId = getOpenIdUtil.getopenid(appid,body.getCode(),secret);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("登录失败");
            }
            JSONObject jsonObject = JSONObject.parseObject(jsonId);
            String openid = jsonObject.getString("openid");
            T06 t06= null;
            try {
                t06 = t06Service.selectByOpneid(openid);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String token  = null ;
            if(t06 == null){
                int cont = sysUserService.getTotal();
                String account = "WeiXinUSer"+String.valueOf(cont+1);
                RegisterBody registerBody = new RegisterBody();
                registerBody.setUsername(account);
                registerBody.setName("微信用户"+String.valueOf(cont+1));
                registerBody.setPassword("123456");
                registerBody.setOpenid(openid);
                aiService.register(registerBody);

                token =xcxLoginService.login(account,"123456");
            }else{
                token =xcxLoginService.login(t06.getF0603(),"123456");
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            return AjaxResult.success(token);
        }
    @ApiOperation("创建会话")
    @Log(title = "会话日志", businessType = BusinessType.RESERCH)
    @PostMapping("/ask/ans")
    public AjaxResult wenda(HttpServletRequest request,@RequestBody String  msg ) throws IOException, ExecutionException, InterruptedException {
        return aiService.wenda(msg,request);
    }
    @ApiOperation("注册")
    @PostMapping("/register1")
    public AjaxResult register(HttpServletRequest request,@RequestBody RegisterBody registorBody) {
        String msg=aiService.register(registorBody);
        if (msg.isEmpty()){
            return AjaxResult.success();
        }
        return new AjaxResult(HttpStatus.BAD_REQUEST,msg);
    }
    @ApiOperation("获取用户信息")
    @Log(title = "小程序日志")
    @GetMapping("/wx/userinfo")
    public AjaxResult getUserInfo(HttpServletRequest request) {
        Long userId = tokenService.getLoginUser(request).getUser().getUserId();
//        T06 t06 = (T06) redisTemplate.opsForValue().get("loginuser:"+userId);
//        if(ObjectUtils.isEmpty(t06)){
//            return AjaxResult.success(t06Service.selectT06ByF0601(userId));
//        }
//        if(t06!=null){
//            return AjaxResult.success(t06);
//        }
//        return new AjaxResult(500, "用户信息获取失败");
        return AjaxResult.success(t06Service.selectT06ByF0601(userId));
    }
    @ApiOperation("今日数据")
    @GetMapping("/wx/todaytoken")
    @Log(title = "小程序日志")
    public AjaxResult getToday(HttpServletRequest request) {
        Long userId = tokenService.getLoginUser(request).getUser().getUserId();
        return AjaxResult.success(t07Service.counttoken(userId));
    }
    @PostMapping(value = "/wx/uploadimage")
    @Log(title = "小程序日志")
    public Result uploadReport(HttpServletRequest request, @RequestBody MultipartFile file) {
        try {
            Long userId = tokenService.getLoginUser(request).getUser().getUserId();
            String filename = file.getOriginalFilename();
            boolean flag=aiService.updateUserImg(file,userId,filename);
            redisTemplate.opsForValue().set("loginuser:"+userId,t06Service.selectT06ByF0601(userId), 30, TimeUnit.MINUTES);
            return Result.success(filename,"上传成功");
        } catch (Exception e) {
            return Result.erro("上传失败");
        }
    }
    @PostMapping("/wx/preview")
    @Log(title = "小程序日志")
    public AjaxResult preview(HttpServletRequest request,@RequestBody String fileName) {
        return AjaxResult.success(minioUtil.getFileUrl(fileName));
    }
    @PostMapping("/wx/update")
    @Log(title = "小程序日志")
    public AjaxResult update(HttpServletRequest request,@RequestBody T06 t06) {
        t06.setF0610(1L);
        int s=t06Service.updateT06(t06);
        if (s==0)
        {
            return AjaxResult.warn("修改失败");
        }
        redisTemplate.opsForValue().set("loginuser:"+t06.getF0601(),t06Service.selectT06ByF0601(t06.getF0601()), 30, TimeUnit.MINUTES);
        return AjaxResult.success("修改成功");
    }
    @PostMapping("/wx/addActivity")
    @Log(title = "小程序日志")
    @ApiOperation("添加流程")
    public AjaxResult addActivity(HttpServletRequest request,@RequestBody T06 t06) {
        try {
            int s=t06Service.addActivity(t06);
            return  AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error("修改失败");
        }
    }

    @GetMapping("/wx/czrecord")
    @Log(title = "小程序日志")
    public AjaxResult getCzrecord(HttpServletRequest request) {
        Long userId = tokenService.getLoginUser(request).getUser().getUserId();
        T10 t10=new T10();
        t10.setF0601(userId);
        List<T10> list =t10Service.selectT10List(t10);
        return AjaxResult.success(list);
    }
    @GetMapping("/wx/QueryTrends")
    @Log(title = "小程序日志")
    public AjaxResult QueryTrends(HttpServletRequest request) {
        Long userId = tokenService.getLoginUser(request).getUser().getUserId();
        List<QUTH> list = aiService.QueryTrends(userId);
        return AjaxResult.success(list);
    }

    @GetMapping("/wx/getsele")
    @Log(title = "小程序日志")
    public AjaxResult getPayRecords(HttpServletRequest request) {
        Long userId = tokenService.getLoginUser(request).getUser().getUserId();
        List<T07> list = t07Service.selectlist(userId);
        return AjaxResult.success(list);
    }
    @GetMapping("/wx/getCom")
    @Log(title = "小程序日志")
    public AjaxResult getT03List(HttpServletRequest request) {
        List<T03> list = aiService.getT03List();
        return AjaxResult.success(list);
    }
    @GetMapping("/wx/getDept/{ComId}")
    @Log(title = "小程序日志")
    public AjaxResult getDept(HttpServletRequest request,@PathVariable("ComId") Long ComId) {
        List<T05> list = aiService.getT05List(ComId);
        return AjaxResult.success(list);
    }
    @PostMapping("/wx/updateById")
    @Log(title = "小程序日志")
    public AjaxResult updateById(HttpServletRequest request,@RequestBody T06 t06) {
        try {
            int x= t06Service.updateT06(t06);
            redisTemplate.opsForValue().set("loginuser:"+t06.getF0601(),t06Service.selectT06ByF0601(t06.getF0601()), 30, TimeUnit.MINUTES);
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    @PostMapping("/wx/cz")
    @Log(title = "小程序日志")
    public AjaxResult cz(HttpServletRequest request,@RequestBody Long f1002) {

        System.out.println(f1002.getClass());
        Long userId = tokenService.getLoginUser(request).getUser().getUserId();
        T06 t06 = t06Service.selectT06ByF0601(userId);
        Long tatel=(Long) t06.getF0611()+f1002*208;
        t06.setF0611(tatel);
        t06Service.updateT06(t06);
        T10 t10=new T10();
        t10.setF0301(t06.getF0301());
        t10.setF0601(t06.getF0601());
        t10.setF1002(f1002);
        Date date = new Date();
        t10.setF1003(date);
        t10.setF1005(tatel);
        t10.setF1007(t06.getF0602());
        t10Service.insertT10(t10);
        redisTemplate.opsForValue().set("loginuser:"+t06.getF0601(),t06Service.selectT06ByF0601(t06.getF0601()), 30, TimeUnit.MINUTES);
        return AjaxResult.success("充值成功");
    }

    @GetMapping("/wx/getHot")
    @Log(title = "小程序日志")
    public AjaxResult getHot(HttpServletRequest request) {
        List<String> list = aiService.getHot(request);
        return AjaxResult.success(list);
    }
}
